from sqlalchemy.orm import Session
from app.core.database import SessionLocal, engine
from app.core.security import get_password_hash
from app.models import User, Department, UserRole, Base

def init_db():
    """初始化数据库"""
    # 创建所有表
    Base.metadata.create_all(bind=engine)
    
    db = SessionLocal()
    
    try:
        # 创建默认部门
        if not db.query(Department).first():
            departments = [
                Department(name="技术部", description="负责技术开发和维护"),
                Department(name="市场部", description="负责市场推广和销售"),
                Department(name="人事部", description="负责人力资源管理"),
                Department(name="财务部", description="负责财务管理")
            ]
            
            for dept in departments:
                db.add(dept)
            db.commit()
            
            print("默认部门创建成功")
        
        # 创建默认管理员用户
        if not db.query(User).filter(User.username == "admin").first():
            tech_dept = db.query(Department).filter(Department.name == "技术部").first()
            
            admin_user = User(
                username="admin",
                email="admin@example.com",
                hashed_password=get_password_hash("admin123"),
                full_name="系统管理员",
                role=UserRole.ADMIN,
                department_id=tech_dept.id if tech_dept else None
            )
            
            db.add(admin_user)
            db.commit()
            
            print("默认管理员用户创建成功: admin / admin123")
        
        # 创建默认普通用户
        if not db.query(User).filter(User.username == "user").first():
            market_dept = db.query(Department).filter(Department.name == "市场部").first()
            
            normal_user = User(
                username="user",
                email="user@example.com",
                hashed_password=get_password_hash("user123"),
                full_name="普通用户",
                role=UserRole.USER,
                department_id=market_dept.id if market_dept else None
            )
            
            db.add(normal_user)
            db.commit()
            
            print("默认普通用户创建成功: user / user123")
            
    except Exception as e:
        print(f"初始化数据库时出错: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    init_db()